import React, { useEffect, useState } from "react";
import {
  Card,
  Row,
  Col,
  Select,
  message,
  Form,
  Cascader,
  DatePicker,
  Button,
} from "antd";
import { SearchOutlined, SyncOutlined } from "@ant-design/icons";
import "../style.css";
import "../../../DepartmentManage/views/style.css";
import AtSchoolPie from "./AtSchoolPie";
import AtSchoolTable from "./AtSchoolTable";
import { fetchRequest } from "../../../../utils/Request";
import { url } from "../../../../utils/url";
import { useRequest } from "@umijs/hooks";
import { Store } from "rc-field-form/lib/interface";
import moment from "moment";

export default function SchoolAnalysis() {
  interface requestParamPie {
    deptId: null | undefined | string;
    startDate: null | undefined | string;
    endDate: null | undefined | string;
  }

  interface requestParamTable {
    deptId: null | undefined | string;
    startDate: null | undefined | string;
    endDate: null | undefined | string;
    pageNum: number;
    pageSize: number;
    schoolMark: number;
  }

  interface requestParamTree {
    level: number;
    treeId: null | undefined | string;
  }

  const [requestParamTable, setRequestParamTable] = useState<requestParamTable>(
    {
      deptId: "",
      startDate: "",
      endDate: "",
      pageNum: 1,
      pageSize: 10,
      schoolMark: 2,
    }
  );
  const [requestParamPie, setRequestParamPie] = useState<requestParamPie>({
    deptId: "",
    startDate: "",
    endDate: "",
  });
  const [requestParamTree, setRequestParamTree] = useState<requestParamTree>({
    level: 0,
    treeId: "0",
  });
  const [statisticData, setStatisticData] = useState<any>([]);
  const [tableData, setTableData] = useState<any>([]);
  const [treeNode, setTreeNode] = useState<any>([]);

  const [form] = Form.useForm();
  const { Option } = Select;

  useEffect(() => {
    if (
      isNull(requestParamTable.deptId) ||
      isNull(requestParamTable.startDate) ||
      isNull(requestParamTable.endDate)
    ) {
      //doNothing
    } else {
      getAtSchoolPieDataRequest(requestParamTable);
    }
  }, [requestParamTable]);

  useEffect(() => {
    getSchoolOrganizationRequest(requestParamTree);
  }, [requestParamTree]);

  useEffect(() => {
    console.log(tableData);
  }, [tableData]);
  //请求在校学生饼图参数
  async function getAtSchoolPieDataRequest(params: requestParamPie) {
    try {
      const json = await fetchRequest(url.GET_QUERY_NUMBER, params);
      if (json.success) {
        setStatisticData([
          {
            name: "在校",
            value: json.data.queryNumberOfSchoolResultVO.atSchool,
          },
          {
            name: "不在校",
            value: json.data.queryNumberOfSchoolResultVO.outSchool,
          },
          {
            name: "未知",
            value: json.data.queryNumberOfSchoolResultVO.unknownSchool,
          },
        ]);
        setTableData(json.data.myPager);
        message.destroy();
      } else {
        message.destroy();
        message.error(json.errorMsg);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  //请求在校学生组织机构
  async function getSchoolOrganizationRequest(params: requestParamTree) {
    try {
      const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION, params);
      if (json.success) {
        message.destroy();
        json.data.forEach((item: any) => {
          delete item.children;
        });
        setTreeNode(json.data);
      } else {
        message.destroy();
        message.error(json.errorMsg);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const getSchoolOrganizationData = useRequest(getSchoolOrganizationRequest, {
    loadingDelay: 200,
    manual: true,
  });

  // //请求在校学生组织机构校区以下全部
  // async function getSchoolOrganizationAllRequest(params: any) {
  //     try {
  //         const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION_ALL, params);
  //         if (json.success) {
  //             message.destroy();
  //             console.log(json.data);
  //             setTreeNode(json.data);
  //
  //         } else {
  //             message.destroy();
  //             message.error(json.errorMsg)
  //         }
  //     } catch (error:any) {
  //         message.destroy();
  //         message.error(error.message)
  //
  //     }
  // }
  //
  // const getSchoolOrganizationAllData = useRequest(getSchoolOrganizationAllRequest, {
  //     loadingDelay: 200,
  //     manual: true
  // });

  //级联函数
  const onChange = (value: any, selectedOptions: any) => {
    // console.log(value, selectedOptions);
    // if(value.length == 1){
    //     const params = {collegeId:"",pid:""};
    //     params.collegeId = value[0];
    //     params.pid = value[0];
    //     // console.log(params)
    //     getSchoolOrganizationAllData.run(params);
    // }
  };

  const loadData = (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    //组装参数
    const params: requestParamTree = {
      level: 0,
      treeId: "0",
    };
    selectedOptions.map((item: any) => {
      params.treeId = item.treeId;
      params.level = selectedOptions.length;
    });
    // console.log(params)

    fetchRequest(url.GET_SCHOOL_ORGANIZATION, params)
      .then((json) => {
        if (json.success) {
          console.log(json.data);
          json.data.forEach((item: any) => {
            delete item.children;
          });
          targetOption.children = json.data;
          // console.log(targetOption)
        } else {
          message.error(json.errMsg);
        }
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        targetOption.loading = false;
        //主动刷新页面
        setTreeNode([...treeNode]);
      });
  };

  function isNull(param: any) {
    return param === "" || param === undefined;
  }

  function handleFinish(values: Store) {
    // if(values.deptId ===undefined || values.deptId === "" || values.deptId.length<=1){
    //     message.error("组织机构请至少选择到第二级！");
    if (isNull(values.deptId)) {
      message.error("请选择组织机构！");
      return false;
    }

    if (isNull(values.date)) {
      message.error("请选择进出时间！");
      return false;
    }

    setRequestParamTable({
      // deptId:"118917293861-0813103010314129",
      deptId:
        typeof values.deptId === "undefined"
          ? ""
          : values.deptId[values.deptId.length - 1],
      startDate:
        typeof values.date === "undefined"
          ? ""
          : moment(values.date[0]).format("YYYY-MM-DD HH:mm:ss"),
      endDate:
        typeof values.date === "undefined"
          ? ""
          : moment(values.date[1]).format("YYYY-MM-DD HH:mm:ss"),
      schoolMark: parseInt(values.schoolMark),
      pageNum: 1,
      pageSize: 10,
    });
    setRequestParamPie({
      // deptId:"118917293861-0813103010314129",
      deptId:
        typeof values.deptId === "undefined"
          ? ""
          : values.deptId[values.deptId.length - 1],
      startDate:
        typeof values.date === "undefined"
          ? ""
          : moment(values.date[0]).format("YYYY-MM-DD HH:mm:ss"),
      endDate:
        typeof values.date === "undefined"
          ? ""
          : moment(values.date[1]).format("YYYY-MM-DD HH:mm:ss"),
    });

    // console.log(requestParamTable);
    // console.log(requestParamPie);
  }

  //点击重置按钮
  function handleReset() {
    form.resetFields();
    setRequestParamTable({
      deptId: "",
      startDate: "",
      endDate: "",
      schoolMark: parseInt("2"),
      pageNum: 1,
      pageSize: 10,
    });
    setRequestParamPie({
      deptId: "",
      startDate: "",
      endDate: "",
    });
  }

  //查询框
  const searchForm = (
    <Card className="search-form">
      {" "}
      <Form
        form={form}
        layout="inline"
        initialValues={{ schoolMark: "2" }}
        onFinish={handleFinish}
        onReset={handleReset}
      >
        <Form.Item className="form-control-item" name="deptId" label="组织机构">
          <Cascader
            placeholder=""
            options={treeNode}
            loadData={loadData}
            changeOnSelect
            onChange={onChange}
            style={{ width: 400 }}
          />
        </Form.Item>

        <Form.Item className="form-control-item" name="date" label="进出时间">
          <DatePicker.RangePicker showTime />
        </Form.Item>

        <Form.Item
          className="form-control-item"
          name="schoolMark"
          label="是否在校"
        >
          <Select style={{ width: 120 }}>
            <Option key="1" value="1">
              在校
            </Option>
            <Option key="2" value="2">
              不在校
            </Option>
          </Select>
        </Form.Item>

        <Form.Item className="form-control-item">
          <Button
            key="1"
            type="primary"
            icon={<SearchOutlined />}
            htmlType="submit"
            style={{ marginRight: "8px" }}
          >
            搜索
          </Button>
          <Button key="2" icon={<SyncOutlined />} htmlType="reset">
            重置
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );

  return (
    <div>
      {searchForm}
      <div className="site-card-border-less-wrapper">
        <Row gutter={24}>
          <Col span={12}>
            <AtSchoolPie data={statisticData} />
          </Col>
          <Col span={12}>
            <AtSchoolTable params={requestParamTable} tableDatas={tableData} />
          </Col>
        </Row>
      </div>
    </div>
  );
}
